package com.designpatterns.ProducerConsumer;

import java.util.concurrent.TimeUnit;

/**
 * Created by 41579 on 2017/6/8.
 */
public class ProducerConsumerBridge {
    private static final int MAX = 10;
    private MyLinkedList<Resource> resourceList = new MyLinkedList<Resource>();

    public void produce() throws InterruptedException {
        synchronized (this) {
            System.out.println("\n\n");
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝");
            System.out.println("begin produce....");
            TimeUnit.SECONDS.sleep(3);
            Resource resource = new Resource(Thread.currentThread().getName());
            while (resourceList.size() >= MAX) {
                System.out.println("waitting produce....");
                wait();
            }
            resourceList.add(resource);
            System.out.println("end produce now have:"+resourceList.toString());
            this.notifyAll();
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝\n\n\n");
        }
    }

    public Resource consume() throws InterruptedException {
        synchronized (this) {
            System.out.println("\n\n");
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝");
            System.out.println("begin consume...");
            TimeUnit.SECONDS.sleep(3);
            while (resourceList.size() <= 0) {
                System.out.println("waiting consume...");
                this.notifyAll();
                wait();
            }
            Resource resource = resourceList.removeFirst();
            System.out.println("end consume now have:"+resourceList.toString());
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝\n\n\n");
            return resource;

        }
    }
}
